//
//  DownloadViewController.m
//  大文件下载
//
//  Created by GR on 2017/9/2.
//  Copyright © 2017年 Harry. All rights reserved.
//

#import "DownloadViewController.h"
#define kCachePath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"cache.plist"]

#define FileCachePath(a) [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:a]

@interface DownloadViewController ()
@property (assign, nonatomic) NSInteger totalSize;
@property (assign, nonatomic) NSInteger currentSize;
@property (strong, nonatomic) NSURLConnection *connection;


@property (copy, nonatomic) NSString *sandBoxPath;
@property (copy, nonatomic) NSString *requestURLString;

@property (strong, nonatomic) NSOutputStream *stream;

@property (strong, nonatomic) NSMutableDictionary *cacheDictM;

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@end

@implementation DownloadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self searchCacheWithURL:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
}

/**
 *  用getFileSizeWithFileName方法获取当前文件大小。不用再将接收到的文件大小进行缓存了。
 *  这样只需要在接收到响应的时候缓存，fileName 和 totalSize就可以了。
 *
 */
- (void)searchCacheWithURL:(NSString *)url
{
    // 1. 获取缓存数据
    self.cacheDictM = [NSMutableDictionary dictionaryWithContentsOfFile:kCachePath];
    if (nil == self.cacheDictM) {
        self.cacheDictM = [NSMutableDictionary dictionaryWithCapacity:0];
    }
    
    // 2. 获取文件数据
    NSMutableDictionary *fileInfoDic = [self.cacheDictM objectForKey:url];
    if (nil == fileInfoDic) {
        fileInfoDic = [NSMutableDictionary dictionaryWithCapacity:0];
        [fileInfoDic setObject:[url lastPathComponent] forKey:@"fileName"];
        [fileInfoDic setObject:@0 forKey:@"totalSize"];
        
        [self.cacheDictM setObject:fileInfoDic forKey:url];
        
        self.totalSize =
        self.currentSize = 0;
    }
    else {
        self.totalSize = [fileInfoDic[@"totalSize"] integerValue];
        self.currentSize = [self getFileSizeWithFileName:fileInfoDic[@"fileName"]];
    }
    
    // 3. 获取文件在沙盒中的位置
    self.sandBoxPath = FileCachePath(fileInfoDic[@"fileName"]);
    
    self.stream = [NSOutputStream outputStreamToFileAtPath:self.sandBoxPath append:YES];
    [self.stream open];
    
    self.requestURLString = url;
    
    // 4. UI设置
    self.progressView.progress = self.totalSize == 0 ? 0 : 1.0f * self.currentSize / self.totalSize;
    
}

- (NSInteger)getFileSizeWithFileName:(NSString *)fileName
{
    NSDictionary *fileInfoDict = [[NSFileManager defaultManager] attributesOfItemAtPath:FileCachePath(fileName) error:nil];
    return [fileInfoDict[@"NSFileSize"] integerValue];
}

- (void)recordFileInfo
{
    NSMutableDictionary *fileInfoDictM = [self.cacheDictM objectForKey:self.requestURLString];
    if (fileInfoDictM) {
        [fileInfoDictM setObject:@(self.totalSize) forKey:@"totalSize"];
    }
    else {
        [fileInfoDictM setObject:@(self.totalSize) forKey:@"totalSize"];
        [fileInfoDictM setObject:[self.requestURLString lastPathComponent] forKey:@"fileName"];
        [self.cacheDictM setObject:fileInfoDictM forKey:self.requestURLString];
    }
    
    [self.cacheDictM writeToFile:kCachePath atomically:YES];
}

- (NSURLConnection *)connection {
    
    if (!_connection) {
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.requestURLString]];
        NSString *range = [NSString stringWithFormat:@"bytes=%zd-", self.currentSize];
        [request setValue:range forHTTPHeaderField:@"Range"];
        
        _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    }
    return _connection;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if (0 == self.totalSize) {
        self.totalSize = response.expectedContentLength;
        
        // 主要记录totalSize
        [self recordFileInfo];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.stream write:data.bytes maxLength:data.length];
    
    self.currentSize += data.length;
    CGFloat progress = 1.0 * self.currentSize / self.totalSize;
    self.progressView.progress = progress;
    
    NSLog(@"%lf",progress);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    self.connection = nil;
    [self.stream close];
    self.stream = nil;
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.stream close];
    self.stream = nil;
    
    NSLog(@"%@", self.sandBoxPath);
    
    [self.cacheDictM removeObjectForKey:self.requestURLString];
    [self.cacheDictM writeToFile:kCachePath atomically:YES];
}

- (IBAction)start:(id)sender {
    [self connection];
}

- (IBAction)pause:(id)sender {
    [self.connection cancel];
    self.connection = nil;
}

- (IBAction)resume:(id)sender {
    [self connection];
}

- (IBAction)clearCache:(id)sender {
    [self.cacheDictM removeObjectForKey:self.requestURLString];
    [self.cacheDictM writeToFile:kCachePath atomically:YES];
    
    [[NSFileManager defaultManager] removeItemAtPath:self.sandBoxPath error:nil];
    
    self.currentSize = 0;
    self.totalSize = 0;
    
    self.progressView.progress = 0;
}
@end
